package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserReportVO;
import com.sun.net.httpserver.HttpsParameters;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.tomcat.util.http.Parameters;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImp implements UserService {
    private final String url = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    WeChatProperties weChatProperties;


    @Resource
    UserMapper userMapper;

    @Override
    public User login(UserLoginDTO loginDTO) {
        //第一步发送请请求获取openid
        String s = getOpenId(loginDTO.getCode());
        JSONObject jsonObject = JSON.parseObject(s);
        String  openid = (String) jsonObject.get("openid");
        if(openid==null){
             throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
         }
         //判断当前用户是否为新用户
         User user = userMapper.getByOpenId(openid);
         if(user==null){
           user =   User.builder().openid(openid).createTime(LocalDateTime.now()).build();
           userMapper.insert(user);
         }

        return user;
    }



    private String getOpenId(String code) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("appid", weChatProperties.getAppid());
        hashMap.put("secret", weChatProperties.getSecret());
        hashMap.put("js_code", code);
        hashMap.put("grant_type", "authorization_code");
        String s = HttpClientUtil.doGet(url, hashMap);
        return s;
    }
}
